package com.sentinel.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.fastjson.JSON;
import com.sentinel.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 谢阳
 * @version 1.0
 * @date 2023/11/22 17:33
 * @description
 */
@Slf4j
@Component
public class GlobalSentinelHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        Result result = null;
        if (e instanceof FlowException) {
            result = Result.failure(HttpStatus.TOO_MANY_REQUESTS.value(), "接口被限流了");
        } else if (e instanceof DegradeException) {
            result = Result.failure(HttpStatus.TOO_MANY_REQUESTS.value(), "服务降级了");
        } else if (e instanceof ParamFlowException) {
            result = Result.failure(HttpStatus.TOO_MANY_REQUESTS.value(), "热点参数限流了");
        } else if (e instanceof AuthorityException) {
            result = Result.failure(HttpStatus.UNAUTHORIZED.value(), "授权规则不通过");
        }
        log.info("sentinel 异常 ===> [{}]", result);
        Object json = JSON.toJSON(result);
        httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(json);
        writer.close();
    }
}
